package diversion.v1.network;

import diversion.v1.security.KeyGen;
import diversion.v1.util.Base64;
import java.io.IOException;
import java.net.Socket;
import java.security.KeyPair;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;

/**
 *  Description of the Class
 *
 * @author    jmricker
 */
public class Client {
    private transient DHPrivateKey privateKey;
    private DHPublicKey            publicKey;
    private String                 publicKeyString;

    /**
     *  Constructor for the Server object
     *
     * @param  serverKeys  Description of the Parameter
     */
    public Client(KeyPair clientKeys, String username, String location) {
        this.publicKey       = (DHPublicKey) clientKeys.getPublic();
        this.privateKey      = (DHPrivateKey) clientKeys.getPrivate();
        this.publicKeyString = Base64.encodeBytes(this.publicKey.getEncoded());
    }

    /**
     *  Description of the Method
     *
     * @param  port     Description of the Parameter
     * @param  address  Description of the Parameter
     */
    public void open(String address, int port) throws IOException {
        Socket  socket = new Socket(address, port);
        doComms conn_c = new doComms(socket, new ServerDispatcher());
        Thread  t      = new Thread(conn_c);

        t.start();
    }

    /**
     *  The main program for the Server class
     *
     * @param  args  The command line arguments
     */
    public static void main(String[] args) {
        KeyPair keys = null;

        try {
            keys = KeyGen.loadKeys("client.key");
        } catch (IOException ie) {
            System.out.println("Client Keys not found.");
        }

        if (keys == null) {
            try {
                keys = KeyGen.generateKeys();
            } catch (java.security.GeneralSecurityException e) {
                System.out.println("Fatal Error: " + e);

                return;
            }

            KeyGen.saveKeys("client.key", keys);
        }

        Client c = new Client(keys, "Joel", "Fuquay-Varina");
        
        try {

            c.open("127.0.0.1", 4444);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}